//
//  YAUserAcountVM.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/5.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import ReactiveCocoa
class YAUserAcountVM: NSObject {
    //单例
    static let sharedUserAccount = YAUserAcountVM()
    var userAcount:YAUserAcount?
    override init(){
        userAcount = YAUserAcount.loadUserAcount()
    }
    var accessToken:String?{
        return userAcount?.access_token
    }
    var userLogon:Bool {
        return accessToken != nil
    }
    var avatarURL:NSURL?{
        return NSURL(string: userAcount?.avatar_large ?? "")
    }
    func loadUserAccountFromVM(code:String)->RACSignal{
        let netTools = YANetworking.sharedTools
       
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            //定义错误信息的闭包
            let errorClosure = {(error)->Void in
                    subscriber.sendError(error)
            }
            // doNext 是可以给信号增加附加操作，第一个信号完成之后，将第一个信号的 result(令牌) 直接传递给第二个信号(详情)
            // doNext 后面一定要加一个 subscriberXXX，否则 doNext 不会被执行到
            netTools.loadAccessTokenWithCode(code).doNext({ (result) -> Void in
                let account = YAUserAcount(dict: result as! [String:AnyObject])
                self.userAcount = account
                netTools.loadUserInfoFromToos(account.uid!).subscribeNext({(result)->Void in
                    let dict = result as! [String:AnyObject]
                    account.name = dict["name"] as? String
                    account.avatar_large = dict["avatar_large"] as? String
                    account.saveUserAcount()
                    subscriber.sendCompleted()
                    },error:errorClosure)
            }).subscribeError(errorClosure)
            return nil
        })
    }
}
